﻿package net.sealuitk.gadgets 
{
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	import net.sealuitk.gadgets.Button;
	import net.sealuitk.UIConst;
	
	/**
	 * ...
	 * @author mkn
	 */
	public class ButtonClick extends Button
	{
		private var clickMode:String;
		
		public static const CLICK_DELAY:String = "delay";
		public static const CLICK_HOLD:String = "hold";
		
		private var clickTimer:Timer = new Timer(250, 1);
		
		public function ButtonClick(Name:String, GraphicsMode:String = UIConst.GRAPHICS_FIXED, ClickMode:String = CLICK_DELAY) 
		{
			super(Name, GraphicsMode);
			clickMode = ClickMode;
			buildEventListener();
		}
		
		public function setClickMode(newMode:String):void {
			if (newMode != CLICK_DELAY && newMode != CLICK_HOLD ) throw Error ("Unknown clickMode: " + newMode);
			else clickMode = newMode;
			updatePopUpEventListener();
		}
		
		/* ================ Event Listener ================
		 * 
		 */
		
		override protected function buildEventListener():void {
			addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
			addEventListener(MouseEvent.ROLL_OVER, mouseOver);
			addEventListener(MouseEvent.ROLL_OUT, mouseOut);
			
			updatePopUpEventListener();
		}
		
		protected function updatePopUpEventListener():void {
			if(hasEventListener(TimerEvent.TIMER) == false) clickTimer.addEventListener(TimerEvent.TIMER, popUp);
			
			switch(clickMode) {
				case CLICK_DELAY:
					if (hasEventListener(MouseEvent.MOUSE_UP) ) removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
				break;
				case CLICK_HOLD:
					if (hasEventListener(MouseEvent.MOUSE_UP) == false) addEventListener(MouseEvent.MOUSE_UP, mouseUp);
				break;
			}
		}
		
		protected function popUp(e:TimerEvent):void {
			setTo(UIConst.STATE_UP);
		}
		
		override protected function mouseDown(e:MouseEvent):void {
			if (state == UIConst.STATE_UP || state == UIConst.STATE_OVER) {
				setTo(UIConst.STATE_DOWN);
				if(clickMode == CLICK_DELAY) clickTimer.start();
			}
		}
		
		protected function mouseUp(e:MouseEvent):void {
			setTo(UIConst.STATE_UP);
		}
		
		override protected function mouseOver(e:MouseEvent):void {
			if (state == UIConst.STATE_UP) {
				setTo(UIConst.STATE_OVER);
			} else if (state == UIConst.STATE_DOWN) {
				setTo(UIConst.STATE_DOWNOVER);
			}
		}
		
		override protected function mouseOut(e:MouseEvent):void {
			setTo(UIConst.STATE_UP);
		}
		
		// ======== Getters & Setters ========
		
		public function get delay():int { return clickTimer.delay; }
		
		public function set delay(value:int):void {
			clickTimer.delay = value;
		}
	}

}